package com.chexiehui.jc.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusRelativeLayout;
import com.aries.ui.view.radius.RadiusTextView;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseActivity;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.entity.AuthInfo;
import com.chexiehui.jc.entity.UserInfo;
import com.chexiehui.jc.event.ReceiveRegistrationIdEvent;
import com.chexiehui.jc.mvp.login.LoginCovenant;
import com.chexiehui.jc.mvp.login.LoginPresenter;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.CodeCountDownTimer;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.utils.SerializableSpTools;

import org.greenrobot.eventbus.Subscribe;

import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * 登录
 */
public class LoginActivity extends BaseMvpActivity<LoginPresenter> implements LoginCovenant.View {

    @BindView(R.id.tv_login_tip)
    TextView tvLoginTip;
    @BindView(R.id.tv_page_title)
    TextView tvPageTitle;
    @BindView(R.id.rl_head_container)
    RelativeLayout rlHeadContainer;
    @BindView(R.id.tv_phone_login_phone_pre)
    TextView tvPhoneLoginPhonePre;
    @BindView(R.id.et_phone_login_phone)
    EditText etPhoneLoginPhone;
    @BindView(R.id.tv_phone_login_get_code)
    TextView tvPhoneLoginGetCode;
    @BindView(R.id.tv_phone_login_code_pre)
    TextView tvPhoneLoginCodePre;
    @BindView(R.id.et_phone_login_code)
    EditText etPhoneLoginCode;
    @BindView(R.id.rtv_phone_login_submit)
    RadiusTextView rtvPhoneLoginSubmit;
    @BindView(R.id.tv_target_login_type)
    TextView tvTargetLoginType;
    @BindView(R.id.rl_login_by_wb)
    RadiusRelativeLayout rlLoginByWb;
    @BindView(R.id.rl_login_by_wx)
    RadiusRelativeLayout rlLoginByWx;
    @BindView(R.id.ll_phone_login_panel)
    LinearLayout llPhoneLoginPanel;
    @BindView(R.id.et_account_login_phone)
    EditText etAccountLoginPhone;
    @BindView(R.id.et_account_password)
    EditText etAccountPassword;
    @BindView(R.id.tv_account_login_find_password)
    TextView tvAccountLoginFindPassword;
    @BindView(R.id.rtv_account_login_submit)
    RadiusTextView rtvAccountLoginSubmit;
    @BindView(R.id.ll_account_login_panel)
    LinearLayout llAccountLoginPanel;
    private CodeCountDownTimer phoneLoginTimer;

    private String registrationId = "";

    // 0 手机号验证码登录 1 账号密码登录
    private int loginType = 0;

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Subscribe
    public void onReceiveRegistrationIdEvent(ReceiveRegistrationIdEvent event){
        if(event != null && !StringUtils.isTrimEmpty(event.getRegistrationId())){
            registrationId = event.getRegistrationId();
            rtvAccountLoginSubmit.setEnabled(true);
        }
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("")
                .setBgColor(ContextCompat.getColor(mContext, R.color.colorTransparent))
                .setOnLeftTextClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        if(loginType == 1){
                            changeLoginType(0);
                        }else {
                            onBackPressed();
                        }
                    }
                });
    }

    private void changeLoginType(int type){
        loginType = type;
        if(loginType == 0){
            titleBar.setLeftTextDrawable(0);
            llPhoneLoginPanel.setVisibility(View.VISIBLE);
            llAccountLoginPanel.setVisibility(View.GONE);
        }else{
            titleBar.setLeftTextDrawable(R.drawable.ic_svg_back);
            llPhoneLoginPanel.setVisibility(View.GONE);
            llAccountLoginPanel.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView(Bundle var1) {
        registrationId = JPushInterface.getRegistrationID(mContext);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) rlHeadContainer.getLayoutParams();
        lp.width = ScreenUtils.getScreenWidth();
        lp.height = BigDecimal.valueOf(lp.width).multiply(BigDecimal.valueOf(201))
                .divide(BigDecimal.valueOf(375), 2, BigDecimal.ROUND_HALF_UP).intValue();
        rlHeadContainer.setLayoutParams(lp);
        changeLoginType(0);
        rtvPhoneLoginSubmit.setEnabled(false);
        rtvAccountLoginSubmit.setEnabled(!StringUtils.isTrimEmpty(registrationId));
        SpannableString spannableString = new SpannableString("登录即同意“用户协议”和“隐私政策”");
        ForegroundColorSpan colorSpan1 = new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.app_color));
        spannableString.setSpan(colorSpan1, 5, 11, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        ClickableSpan clickableSpan1 = new ClickableSpan() {

            @Override
            public void onClick(@NonNull View widget) {
                startActivity(WebActivity.class, new BundleBuilder().putString("url", Constants.YRL_CYHYHXY).create());
            }
        };
        spannableString.setSpan(clickableSpan1,5, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ForegroundColorSpan colorSpan2 = new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.app_color));
        spannableString.setSpan(colorSpan2, 12, 18, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        ClickableSpan clickableSpan2 = new ClickableSpan() {

            @Override
            public void onClick(@NonNull View widget) {
                startActivity(WebActivity.class, new BundleBuilder().putString("url", Constants.YRL_CYHYSZC).create());
            }
        };
        spannableString.setSpan(clickableSpan2,12, 18, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvLoginTip.setText(spannableString);
        tvLoginTip.setMovementMethod(LinkMovementMethod.getInstance());

    }

    @OnClick({R.id.tv_phone_login_get_code, R.id.rtv_phone_login_submit, R.id.tv_target_login_type,
            R.id.rl_login_by_wb, R.id.rl_login_by_wx, R.id.tv_account_login_find_password,
            R.id.rtv_account_login_submit})
    public void onViewClicked(View view) {
        if(NoDoubleClickUtils.isDoubleClick()) return;
        switch (view.getId()) {
            case R.id.tv_phone_login_get_code:
                mvpPresenter.getCodeByPhoneLogin(etPhoneLoginPhone.getText().toString());
                break;
            case R.id.rtv_phone_login_submit:
                mvpPresenter.phoneLogin(etPhoneLoginPhone.getText().toString(), etPhoneLoginCode.getText().toString());
                break;
            case R.id.tv_target_login_type:
                changeLoginType(1);
                break;
            case R.id.rl_login_by_wb:
                break;
            case R.id.rl_login_by_wx:
                break;
            case R.id.tv_account_login_find_password:
                startActivityForResult(FindPasswordActivity.class, 100);
                break;
            case R.id.rtv_account_login_submit:
                mvpPresenter.accountLogin(etAccountLoginPhone.getText().toString(), etAccountPassword.getText().toString());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 100){
            if(resultCode == RESULT_OK){
                startActivity(MainActivity.class);
                finish();
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (loginType == 1) {
            changeLoginType(0);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter(this);
    }

    @Override
    public void onGetCodeByPhoneLoginSuccess(BaseModel<Object> successResult) {
        showToast(String.format(getStringSource(R.string.s_yzmyfs_tips_),
                etPhoneLoginPhone.getText().toString().trim()));
        if(phoneLoginTimer == null){
            phoneLoginTimer = new CodeCountDownTimer(tvPhoneLoginGetCode, 60000, 1000);
        }
        phoneLoginTimer.start();
        rtvPhoneLoginSubmit.setEnabled(true);
    }

    @Override
    public void onGetCodeByPhoneLoginFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onPhoneLoginSuccess(BaseModel<AuthInfo> successResult) {
        SerializableSpTools.putAuthInfo(successResult.getData());
        mvpPresenter.getUserInfo();
    }

    @Override
    public void onPhoneLoginFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onAccountLoginSuccess(BaseModel<AuthInfo> successResult) {
        SerializableSpTools.putAuthInfo(successResult.getData());
        mvpPresenter.getUserInfo();
    }

    @Override
    public void onAccountLoginFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
        SerializableSpTools.clearAuthInfo();
        SerializableSpTools.clearUserInfo();
    }

    @Override
    public void onGetUserInfoSuccess(BaseModel<UserInfo> successResult) {
        SerializableSpTools.putUserInfo(successResult.getData());
        SerializableSpTools.setIsLogin(true);
        startActivity(MainActivity.class);
        finish();
    }

    @Override
    public void onGetUserInfoFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
        SerializableSpTools.clearAuthInfo();
        SerializableSpTools.clearUserInfo();
    }

    @Override
    public String getIm() {
        return registrationId;
    }

    @Override
    protected void onDestroy() {
        if(phoneLoginTimer != null){
            phoneLoginTimer.release();
            phoneLoginTimer = null;
        }
        super.onDestroy();
    }
}
